<template>
    <div class="job-list">
      <!-- 页面头部 -->
      <div class="page-header">
        <h2>岗位列表</h2>
        <div class="header-actions">
          <el-button v-if="showPublish" type="primary" :icon="Plus" @click="handleAddJob">发布岗位</el-button>
        </div>
      </div>
  
      <!-- 筛选和搜索 -->
      <el-card class="filter-card">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索岗位名称、描述、技能标签等"
              :prefix-icon="Search"
              clearable
              @keyup.enter="handleSearch"
              @clear="handleSearch"
            />
          </el-col>
          <el-col :span="4">
            <el-select v-model="statusFilter" placeholder="岗位状态" clearable @change="handleFilter">
              <el-option label="全部" value="all" />
              <el-option label="招聘中" value="active" />
              <el-option label="已暂停" value="inactive" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="categoryFilter" placeholder="岗位分类" clearable @change="handleFilter">
              <el-option label="全部" value="all" />
              <el-option label="技术开发" value="tech" />
              <el-option label="产品管理" value="product" />
              <el-option label="设计" value="design" />
              <el-option label="运营" value="operation" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="locationFilter" placeholder="工作地点" clearable @change="handleFilter">
              <el-option label="全部" value="all" />
              <el-option label="北京" value="beijing" />
              <el-option label="上海" value="shanghai" />
              <el-option label="深圳" value="shenzhen" />
              <el-option label="杭州" value="hangzhou" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
            <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-card>
  
      <!-- 岗位列表 -->
      <div class="jobs-container">
        <div v-loading="loading" class="jobs-grid">
          <div v-for="job in jobs" :key="job.jobId" class="job-card" @click="handleViewJob(job)">
            <div class="job-header">
              <div class="job-title">
                <h3>{{ job.jobName }}</h3>
                <el-tag v-if="job.isTop" type="warning" size="small">置顶</el-tag>
              </div>
              <div class="job-status">
                <el-tag :type="job.jobStatus === 'active' ? 'success' : 'info'">
                  {{ job.jobStatus === 'active' ? '招聘中' : '已暂停' }}
                </el-tag>
              </div>
            </div>
            
            <div class="job-info">
              <div class="job-meta">
                <span class="location">
                  <el-icon><Location /></el-icon>
                  {{ job.location }}
                </span>
                <span class="salary">
                  <el-icon><Money /></el-icon>
                  {{ job.salary }}
                </span>
                <span class="experience">
                  <el-icon><User /></el-icon>
                  {{ job.experience }}
                </span>
              </div>
              
              <div class="job-description">
                <p>{{ job.jobDescription }}</p>
              </div>
              
              <div class="job-tags">
                <el-tag v-for="tag in job.tags" :key="tag" size="small" class="tag">{{ tag }}</el-tag>
              </div>
            </div>
            
            <div class="job-footer">
              <div class="company-info">
                <div class="company-name">{{ job.companyName }}</div>
                <div class="company-meta">
                  <span>{{ job.companySize }}</span>
                  <span>{{ job.companyIndustry }}</span>
                  <div class="rating">
                    <el-icon><Star /></el-icon>
                    {{ job.companyRating }}
                  </div>
                </div>
              </div>
              
              <div class="job-stats">
                <span class="view-count">
                  <el-icon><View /></el-icon>
                  {{ job.viewCount }}
                </span>
              </div>
            </div>
            
            <div class="job-actions">
              <el-button 
                size="small" 
                :type="collectStatusMap.get(job.jobId) ? 'warning' : ''" 
                :icon="collectStatusMap.get(job.jobId) ? StarFilled : Star" 
                @click.stop="handleToggleCollect(job, $event)"
              >
                {{ collectStatusMap.get(job.jobId) ? '已收藏' : '收藏' }}
              </el-button>
              <el-button size="small" @click.stop="handleViewJobDetail(job)">查看详情</el-button>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-if="!loading && jobs.length === 0" class="empty-state">
          <el-empty description="暂无岗位数据">
            <el-button v-if="showPublish" type="primary" @click="handleAddJob">发布第一个岗位</el-button>
          </el-empty>
        </div>
      </div>
  
      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 48, 96]"
          :total="totalJobs"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
  
      <!-- 岗位详情对话框 -->
      <el-dialog
        v-model="jobDetailVisible"
        :title="currentJob?.jobName"
        width="800px"
        :close-on-click-modal="false"
      >
        <div v-if="currentJob" class="job-detail">
          <div class="job-detail-header">
            <div class="job-basic-info">
              <h2>{{ currentJob.jobName }}</h2>
              <div class="job-meta-info">
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="工作地点">
                    {{ currentJob.location }}
                  </el-descriptions-item>
                  <el-descriptions-item label="薪资范围">
                    {{ currentJob.salary }}
                  </el-descriptions-item>
                  <el-descriptions-item label="工作经验">
                    {{ currentJob.experience }}
                  </el-descriptions-item>
                  <el-descriptions-item label="学历要求">
                    {{ currentJob.education }}
                  </el-descriptions-item>
                  <el-descriptions-item label="岗位分类">
                    {{ currentJob.category }}
                  </el-descriptions-item>
                  <el-descriptions-item label="招聘人数">
                    {{ currentJob.hiringCount }}人
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </div>
          
          <div class="job-detail-content">
            <div class="job-detail-description">
              <h3>岗位描述</h3>
              <p>{{ currentJob.jobDescription }}</p>
            </div>
            
            <div class="job-requirements">
              <h3>任职要求</h3>
              <ul>
                <li v-for="requirement in currentJob.requirements" :key="requirement">{{ requirement }}</li>
              </ul>
            </div>
            
            <div class="job-benefits">
              <h3>福利待遇</h3>
              <div class="benefits-tags">
                <el-tag v-for="benefit in currentJob.benefits" :key="benefit" type="success">{{ benefit }}</el-tag>
              </div>
            </div>
            
            <div class="company-info">
              <h3>公司信息</h3>
              <div class="company-detail">
                <div class="company-basic">
                  <h4>{{ currentJob.companyName }}</h4>
                  <p>{{ currentJob.companyDescription }}</p>
                </div>
                <div class="company-meta">
                  <span>公司规模：{{ currentJob.companySize }}</span>
                  <span>所属行业：{{ currentJob.companyIndustry }}</span>
                  <div class="company-rating">
                    <el-icon><Star /></el-icon>
                    {{ currentJob.companyRating }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="jobDetailVisible = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>
  
      <!-- 岗位编辑对话框 -->
      <JobEditDialog
        v-model="jobEditDialogVisible"
        :job-data="currentJobData"
        @success="handleJobSuccess"
      />
  
    </div>
  </template>
  
<script setup>
import { ref, computed, onMounted, defineProps, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import { 
  Plus, 
  Search, 
  Refresh, 
  Location, 
  Money, 
  User, 
  View, 
  Star,
  StarFilled,
  Edit,
  Loading
} from '@element-plus/icons-vue'
import JobEditDialog from '@/components/job/JobEditDialog.vue'
import { getJobList, collectJob, uncollectJob, checkJobCollected } from '@/api/enterprise'
import useStore from '@/store'

const route = useRoute()
const store = useStore()

// 控制前台/后台是否展示"发布岗位"，前台传 false
const { showPublish = true } = defineProps({ showPublish: { type: Boolean, default: true } })

// 获取当前企业ID
const currentEnterpriseId = computed(() => {
  // 优先使用路由参数中的enterpriseId
  if (route.query.enterpriseId) {
    return Number(route.query.enterpriseId)
  }
  // 否则使用store中的enterpriseId
  if (store.app.enterpriseId) {
    return Number(store.app.enterpriseId)
  }
  return null
})

  // 搜索和筛选
  const searchKeyword = ref('')
  const statusFilter = ref('all')
  const categoryFilter = ref('all')
  const locationFilter = ref('all')
  const currentPage = ref(1)
  const pageSize = ref(12)
  const totalJobs = ref(0)
  
  // 搜索状态 - 只有点击搜索后才应用筛选
  const appliedSearchKeyword = ref('')
  const appliedStatusFilter = ref('all')
  const appliedCategoryFilter = ref('all')
  const appliedLocationFilter = ref('all')
  
  // 对话框状态
  const jobDetailVisible = ref(false)
  const jobEditDialogVisible = ref(false)
  const currentJob = ref(null)
  const currentJobData = ref({})
  const activeTab = ref('all')
  
  // 岗位数据
  const jobs = ref([])
  const loading = ref(false)
  
  // 收藏状态
  const collectStatusMap = ref(new Map())
  
  // 获取岗位列表
  const fetchJobs = async () => {
    try {
      loading.value = true
      const params = {
        keyword: appliedSearchKeyword.value,
        status: appliedStatusFilter.value !== 'all' ? appliedStatusFilter.value : undefined,
        category: appliedCategoryFilter.value !== 'all' ? appliedCategoryFilter.value : undefined,
        location: appliedLocationFilter.value !== 'all' ? appliedLocationFilter.value : undefined,
        enterpriseId: currentEnterpriseId.value, // 添加企业ID筛选
        page: currentPage.value,
        pageSize: pageSize.value
      }
      
      console.log(`🔍 获取企业 ${currentEnterpriseId.value} 的岗位列表`, params)
      
      const response = await getJobList(params)
      jobs.value = response?.data?.list || response?.list || []
      totalJobs.value = response?.data?.total || response?.total || 0
      
      console.log(`✅ 获取到 ${jobs.value.length} 个岗位，总计 ${totalJobs.value} 个`)
      
      // 获取收藏状态
      await fetchCollectStatus()
    } catch (error) {
      console.error('获取岗位列表失败:', error)
      ElMessage.error('获取岗位列表失败')
      // 失败时不再使用模拟数据
      jobs.value = []
      totalJobs.value = 0
    } finally {
      loading.value = false
    }
  }
  
  // 搜索处理
  const handleSearch = () => {
    appliedSearchKeyword.value = searchKeyword.value
    appliedStatusFilter.value = statusFilter.value
    appliedCategoryFilter.value = categoryFilter.value
    appliedLocationFilter.value = locationFilter.value
    currentPage.value = 1
    fetchJobs()
  }
  
  // 筛选处理
  const handleFilter = () => {
    handleSearch()
  }
  
  // 重置筛选
  const handleReset = () => {
    searchKeyword.value = ''
    statusFilter.value = 'all'
    categoryFilter.value = 'all'
    locationFilter.value = 'all'
    appliedSearchKeyword.value = ''
    appliedStatusFilter.value = 'all'
    appliedCategoryFilter.value = 'all'
    appliedLocationFilter.value = 'all'
    currentPage.value = 1
    fetchJobs()
  }
  
  // 分页处理
  const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    fetchJobs()
  }
  
  const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchJobs()
  }
  
  // 岗位操作
  const handleViewJob = (job) => {
    currentJob.value = job
    jobDetailVisible.value = true
  }
  
  const handleViewJobDetail = (job) => {
    handleViewJob(job)
  }
  
  const handleAddJob = () => {
    currentJobData.value = {}
    jobEditDialogVisible.value = true
  }
  
  // 岗位操作成功回调
  const handleJobSuccess = () => {
    fetchJobs()
  }
  
  // 获取收藏状态
  const fetchCollectStatus = async () => {
    if (jobs.value.length === 0) return
    
    try {
      const statusChecks = jobs.value.map(job => 
        checkJobCollected(job.jobId).catch(() => ({ data: { isCollected: false } }))
      )
      const results = await Promise.all(statusChecks)
      
      const newMap = new Map()
      jobs.value.forEach((job, index) => {
        newMap.set(job.jobId, results[index]?.data?.isCollected || false)
      })
      collectStatusMap.value = newMap
    } catch (error) {
      console.error('获取收藏状态失败:', error)
    }
  }
  
  // 切换收藏状态
  const handleToggleCollect = async (job, event) => {
    event.stopPropagation()
    
    const jobId = job.jobId
    const isCollected = collectStatusMap.value.get(jobId)
    
    try {
      if (isCollected) {
        await uncollectJob(jobId)
        // 创建新的 Map 以触发响应式更新
        const newMap = new Map(collectStatusMap.value)
        newMap.set(jobId, false)
        collectStatusMap.value = newMap
        ElMessage.success('取消收藏成功')
      } else {
        await collectJob(jobId)
        // 创建新的 Map 以触发响应式更新
        const newMap = new Map(collectStatusMap.value)
        newMap.set(jobId, true)
        collectStatusMap.value = newMap
        ElMessage.success('收藏成功')
      }
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error(isCollected ? '取消收藏失败' : '收藏失败')
    }
  }

  // 监听企业ID变化
  watch(() => currentEnterpriseId.value, (newId, oldId) => {
    if (newId && newId !== oldId) {
      console.log(`🔄 企业ID变化: ${oldId} -> ${newId}, 重新加载岗位列表`)
      currentPage.value = 1 // 重置到第一页
      fetchJobs()
    }
  })
  
  // 初始化数据
  onMounted(() => {
    fetchJobs()
  })
  </script>
  
  <style scoped>
  .job-list {
    padding: 20px;
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .page-header h2 {
    margin: 0;
    color: #333;
  }
  
  .header-actions {
    display: flex;
    gap: 10px;
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .jobs-container {
    margin-bottom: 20px;
  }
  
  .jobs-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .job-card {
    background: white;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 20px;
    cursor: pointer;
    transition: all 0.3s ease;
  }
  
  .job-card:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
  
  .job-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 15px;
  }
  
  .job-title {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .job-title h3 {
    margin: 0;
    color: #333;
    font-size: 18px;
    font-weight: 600;
  }
  
  .job-info {
    margin-bottom: 15px;
  }
  
  .job-meta {
    display: flex;
    gap: 15px;
    margin-bottom: 10px;
    color: #666;
    font-size: 14px;
  }
  
  .job-meta span {
    display: flex;
    align-items: center;
    gap: 4px;
  }
  
  .job-description {
    margin-bottom: 10px;
  }
  
  .job-description p {
    color: #666;
    font-size: 14px;
    line-height: 1.5;
    margin: 0;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  
  .job-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .tag {
    margin: 0;
  }
  
  .job-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
  }
  
  .company-info {
    flex: 1;
  }
  
  .company-name {
    font-weight: 600;
    color: #333;
    margin-bottom: 4px;
  }
  
  .company-meta {
    display: flex;
    align-items: center;
    gap: 10px;
    color: #666;
    font-size: 12px;
  }
  
  .rating {
    display: flex;
    align-items: center;
    gap: 2px;
    color: #f39c12;
  }
  
  .job-stats {
    display: flex;
    gap: 15px;
    color: #666;
    font-size: 12px;
  }
  
  .job-stats span {
    display: flex;
    align-items: center;
    gap: 4px;
  }
  
  .job-actions {
    display: flex;
    gap: 8px;
  }
  
  .empty-state {
    text-align: center;
    padding: 60px 0;
  }
  
  .pagination-section {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  
  .job-detail {
    max-height: 600px;
    overflow-y: auto;
  }
  
  .job-detail-header {
    margin-bottom: 20px;
  }
  
  .job-basic-info h2 {
    margin: 0 0 15px 0;
    color: #333;
  }
  
  .job-detail-content {
    margin-top: 20px;
  }
  
  .job-detail-description,
  .job-requirements,
  .job-benefits,
  .company-info {
    margin-bottom: 20px;
  }
  
  .job-detail-description h3,
  .job-requirements h3,
  .job-benefits h3,
  .company-info h3 {
    margin: 0 0 10px 0;
    color: #333;
    font-size: 16px;
  }
  
  .job-detail-description p {
    color: #666;
    line-height: 1.6;
    margin: 0;
  }
  
  .job-requirements ul {
    margin: 0;
    padding-left: 20px;
  }
  
  .job-requirements li {
    color: #666;
    line-height: 1.6;
    margin-bottom: 5px;
  }
  
  .benefits-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .company-detail {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 6px;
  }
  
  .company-basic h4 {
    margin: 0 0 8px 0;
    color: #333;
  }
  
  .company-basic p {
    color: #666;
    margin: 0 0 10px 0;
    line-height: 1.5;
  }
  
  .company-meta {
    display: flex;
    align-items: center;
    gap: 15px;
    color: #666;
    font-size: 14px;
  }
  
  .company-rating {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #f39c12;
  }
  
  .dialog-footer {
    display: flex;
    gap: 10px;
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
    justify-content: flex-start;
  }
  
  .dialog-footer {
    text-align: right;
  }
  </style>